﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web;
using System.Configuration;

namespace Shop.Common
{
    public class HandleWx
    {
        #region 微信配置信息

        public static string Appid = ConfigurationManager.AppSettings["Appid"];
        public static string AppSecret = ConfigurationManager.AppSettings["AppSecret"]; 
        public static string token = ConfigurationManager.AppSettings["token"];
        public static string Mchid = ConfigurationManager.AppSettings["Mchid"];
        public static string APISecret = ConfigurationManager.AppSettings["APISecret"];
        #endregion 微信配置信息

        #region 获取access_token

        public static string getAccessToken()
        {
            string URL = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", Appid, AppSecret);
            string result = HandleWxHttp.Get(URL);
            var a = HandleJson.GetJsonValue(result);
            string access_token = string.Format("{0}", a["access_token"]);
            return access_token;
        }

        #endregion 获取access_token

        #region 查询菜单
        public static List<WxMenu> getMenu()
        {
            string access_token = getAccessToken();
            string url = string.Format("https://api.weixin.qq.com/cgi-bin/menu/get?access_token={0}", access_token);
            var result = HandleWxHttp.Get(url);
            var btnjson = HandleJson.GetJsonValueSingle(result, "button");
            var a = HandleJson.getJsonValueObj<List<WxMenu>>(result);
            return a;
        }
        #endregion 查询菜单

        #region 通过授权连接获取用户openid

        public static string getOpenId(string code)
        {
            string url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", Appid, AppSecret, code);
            string result = HandleWxHttp.Get(url);
            var a = HandleJson.GetJsonValue(result);
            if (a.ContainsKey("openid"))
                return string.Format("{0}", a["openid"]);
            else
                return "";
        }

        public static string getCusWxOpenId(int IDCus)
        {
            var openid = string.Format("{0}", Common.HandleCookie.GetCookieValue("openid"));
            if (openid.Length > 0)
                return openid;
            else
            {
                StringBuilder sql = new StringBuilder();
                openid = string.Format("{0}", HandleSQL.getObj(string.Format(" SELECT TOP 1 cWX FROM dbo.Customer WHERE ID={0} ", IDCus)));
                return openid;
            }
        }

        #endregion 通过授权连接获取用户openid

        #region 发送消息

        /// <summary>
        /// 发送消息给指定的某微信用户，openid微信用户openid，message消息的具体内容
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public static string SendMessage(string openid, string message)
        {
            string access_token = getAccessToken();
            var json = "{ \"touser\":\"" + openid + "\", \"msgtype\":\"text\", \"text\": { \"content\":\"" + message + "\" }}";
            string url = string.Format("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={0}", access_token);
            return HandleWxHttp.Post(json, url);
        }

        #endregion 发送消息
    }

    public class HandleWxHttp
    {
        public static string Post(string json, string url)
        {
            Stream outstream = null;
            Stream instream = null;
            StreamReader sr = null;
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            Encoding encoding = Encoding.UTF8;
            byte[] data = encoding.GetBytes(json);
            // 准备请求...
            try
            {
                // 设置参数
                request = WebRequest.Create(url) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = data.Length;
                outstream = request.GetRequestStream();
                outstream.Write(data, 0, data.Length);
                outstream.Close();
                //发送请求并获取相应回应数据
                response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                instream = response.GetResponseStream();
                sr = new StreamReader(instream, encoding);
                //返回结果网页（html）代码
                string content = sr.ReadToEnd();
                string err = string.Empty;
                return content;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return string.Empty;
            }
        }

        /// <summary>
        /// 处理http GET请求，返回数据
        /// </summary>
        /// <param name="url">请求的url地址</param>
        /// <returns>http GET成功后返回的数据，失败抛WebException异常</returns>
        public static string Get(string url)
        {
            System.GC.Collect();
            string result = "";

            HttpWebRequest request = null;
            HttpWebResponse response = null;

            //请求url以获取数据
            try
            {
                //设置最大连接数
                ServicePointManager.DefaultConnectionLimit = 200;
                //设置https验证方式
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback =
                            new RemoteCertificateValidationCallback(CheckValidationResult);
                }

                /***************************************************************
                * 下面设置HttpWebRequest的相关属性
                * ************************************************************/
                request = (HttpWebRequest)WebRequest.Create(url);

                request.Method = "GET";

                //设置代理
                //WebProxy proxy = new WebProxy();
                //proxy.Address = new Uri(WxPayConfig.PROXY_URL);
                //request.Proxy = proxy;

                //获取服务器返回
                response = (HttpWebResponse)request.GetResponse();

                //获取HTTP返回数据
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                result = sr.ReadToEnd().Trim();
                sr.Close();
            }
            catch (System.Threading.ThreadAbortException e)
            {
                // Log.Error("HttpService", "Thread - caught ThreadAbortException - resetting.");
                // Log.Error("Exception message: {0}", e.Message);
                System.Threading.Thread.ResetAbort();
            }
            catch (WebException e)
            {
                // Log.Error("HttpService", e.ToString());
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    //Log.Error("HttpService", "StatusCode : " + ((HttpWebResponse)e.Response).StatusCode);
                    //  Log.Error("HttpService", "StatusDescription : " + ((HttpWebResponse)e.Response).StatusDescription);
                }
                //throw new WxPayException(e.ToString());
            }
            catch (Exception e)
            {
                //  Log.Error("HttpService", e.ToString());
                //throw new WxPayException(e.ToString());
            }
            finally
            {
                //关闭连接和流
                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
            }
            return result;
        }

        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            //直接确认，否则打不开
            return true;
        }
    }

    public class WxMenu
    {
        public string type { get; set; }
        public string name { get; set; }
        public string key { get; set; }
        public string url { get; set; }
        public List<WxMenu> sub_button { get; set; }
    }

    public class Wxsubbutton
    {
        public string type { get; set; }
        public string name { get; set; }
        public string key { get; set; }
        public string url { get; set; }
    }

}